<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * @author 
 * @copyright 2011
 */
 
class Authorize extends CI_Controller {

	var $admin_phanmem1='';
	var $taikhoan='';
	function __construct()
	{
		parent::__construct();
		$this->lang->load('title');
        $this->load->model();
		$this->load->model('login_model');
		$this->load->helper('form');
	}
	function  _remap($method, $params = array()){
        if(method_exists($this, $method)){
            return call_user_func_array(array($this, $method), $params);
        }
        $this->_view();
    }
	function _view(){ 
	    $data = new stdClass();
		$this->load->helper('form');
		$this->pub->set_tpl('login');
		$logins = $this->pub->GetSession('login');
		if(!empty($logins['taikhoan'])){
			redirect(base_url().'klgb');	
		}
        $content = $this->load->view('view',$data,true);
        $this->pub->write('content',$content,true);
        $this->pub->render();
	}
	function login()
	{
	   	if(!isset($_POST['captcha']))
             show_404(); 
        
        $sessionValidLogin = (int)$this->pub->GetSession('sessionValidLogin');
        $sessionTimeValidLogin = (int)$this->pub->GetSession('sessionTimeValidLogin');
       // echo time() - (int)$this->pub->config['look_length']*60;
        
        if($sessionValidLogin && time() - (int)$this->pub->config['look_length']*60 > $sessionTimeValidLogin)
        {
			 $this->pub->DeleteSession('sessionValidLogin');
			 $this->pub->DeleteSession('sessionTimeValidLogin');
        }
        
        $this->pub->SetSession('sessionTimeValidLogin',time());     
        
        if($sessionValidLogin >= (int)$this->pub->config['look_count'])
        {
           // $this->pub->SetFlashData('loginerror',3);
            redirect(base_url());
        }
        else
        {
            $user_session = $this->input->post('captcha');
			//$account = $user_session['login'];
            //$password = $user_session['password'];
            //$captcha = $user_session['captcha'];
            $account = $this->input->post('login');;
            $password = $this->input->post('password');
            $captcha = $this->input->post('captcha');

		   	if($account=='admin')
		  		$this->taikhoan='admin';
			else
				$this->admin_phanmem1="  AND `phanmem` LIKE '%,".$this->pub->config['session_name'].",%'";
				
            
            if(strlen($account) < 1 ||  strlen($password) < 1  ||  strlen($captcha) < 1){
                $this->pub->SetFlashData('loginerror',2);
                redirect(base_url());
            }
            
            $captcha = md5($captcha);
            $captcha2 = $this->pub->GetSession('captcha_val');
            
            if($captcha != $captcha2){
				
				//S tinh toan update cho cot trangthai trong table lslogin
						//S viet update du lieu cho bang ls login ben PM quan ly user
						//$users = $this->_GetUser($user);
						$trinhduyets=$_SERVER['HTTP_USER_AGENT'];
						$session_names = $this->pub->config['session_name'];
						$sitenames = $this->pub->config['sitename'];//print_r($session_names.'--'.$sitenames.'--'.json_encode($users).'--');exit;
						$sql_lslogin="INSERT INTO `lslogins` (`taikhoan`, `timedn`, `account`, `ip`, `trinhduyet`,`session_name`,`sitename`,`trangthaidangnhap`) 
						VALUES ('".$account."', '".gmdate("Y-m-d H:i:s",time()+7*3600)."','', '".$_SERVER["REMOTE_ADDR"]."', '".$trinhduyets."','".$session_names."','".$sitenames."',3)";//print_r($sql_lslogin);exit;
						$this->pub->ketnoi_sql($sql_lslogin,'update'); 
						//E viet update du lieu cho bang ls login ben PM quan ly user     
					//E tinh toan update cho cot trangthai trong table lslogin
					
                $this->pub->SetFlashData('loginerror',1);
                //$sessionValidLogin = (int)$this->pub->GetSession('sessionValidLogin');
                $this->pub->SetSession('sessionValidLogin', $sessionValidLogin+1);
                redirect(base_url());
            }
			$arruid = array('mk'=>$password,'uid'=>$account);
			$this->pub->SetSession('mk',$arruid);	
            $checkL = $this->_GetLogin($account,$password);
            if($checkL)
            {
			
                $status = $this->_register($checkL);
            }
            else
            {
                $status = 0;
            }
    	   
            if($status==1)
            {
    			$this->pub->DeleteSession('captcha_val');
                $this->pub->DeleteSession('sessionValidLogin');
                $this->pub->DeleteSession('sessionTimeValidLogin');
    			$start = $this->pub->GetSession('start');
 			    echo 1; //redirect(base_url().'home'.url_suffix());
            
            }
            else if($status==2)
            {    
                $this->pub->SetSession('changepass_time',strtotime(gmdate("H:i:s d-m-Y",time()+7*3600)));
                echo 2;//redirect(base_url().'authorize/changepass'.url_suffix());
            }
            else
            {
                
              $this->pub->SetFlashData('loginerror',1);
              //$sessionValidLogin = (int)$this->pub->GetSession('sessionValidLogin');
              $this->pub->SetSession('sessionValidLogin', $sessionValidLogin+1);             
              echo 0;//redirect(base_url());
            }
        }
    
	}
	
	private function _register($user)
	{
            
            $users = $this->_GetUser($user);
			
            $time_pass = $this->config_model->get('time_pass')*24*3600;
            $time_pass2 = strtotime(gmdate("Y-m-d H:i:s",time()+7*3600)) - strtotime($users['time_change_pass']);
            $sid = md5($users['id']);
            $v = array('time'=>gmdate("Y-m-d H:i:s",time()+7*3600),
                           'ip'=>$_SERVER["REMOTE_ADDR"],
                           'account'=>json_encode($users),
                           'sessionid'=>$sid);
                        
            $this->model->table('logins')->where('sessionid',$sid)->delete();
            $this->model->table('logins')->save('',$v);
			
			//S viet update du lieu cho bang ls login ben PM quan ly user
		 	$trinhduyets=$_SERVER['HTTP_USER_AGENT'];
			$session_names = $this->pub->config['session_name'];
			$sitenames = $this->pub->config['sitename'];//print_r($session_names.'--'.$sitenames.'--'.json_encode($users).'--');exit;
			$sql_lslogin="INSERT INTO `lslogins` (`taikhoan`, `timedn`, `account`, `ip`, `trinhduyet`,`session_name`,`sitename`) 
			VALUES ('".$users['taikhoan']."', '".gmdate("Y-m-d H:i:s",time()+7*3600)."','".json_encode($users)."', '".$_SERVER["REMOTE_ADDR"]."', '".$trinhduyets."','".$session_names."','".$sitenames."')";//print_r($sql_lslogin);exit;
           	$this->pub->ketnoi_sql($sql_lslogin,'update'); 
		//E viet update du lieu cho bang ls login ben PM quan ly user     
		
                
            if($users['doimatkhau'] || ($users['hethanmatkhau'] && $time_pass2>=$time_pass))
            {
                $this->pub->SetSession('login_temp',$users);            
                return 2;
                
            }
            else
            {
                
                $this->pub->SetSession('login',$sid);
                return 1;
            }
	}

	function logout()
	{
		$login = $this->pub->GetSession('login');
		$this->pub->DeleteSession('login'); 
        $this->login_model->Del($login);
		$this->pub->DeleteSession('start');
		$this->pub->DeleteSession('login');
		$this->pub->DeleteSession('mk');
		$this->pub->DeleteSession('current_controll');
  		redirect(base_url());
	}
    
    function changepass(){

       $time =  $this->pub->GetSession('changepass_time');
       
       if(empty($time)) 
       {
            $this->pub->DeleteSession('login_temp');
            $this->pub->DeleteSession('changepass_time');
            echo 1; exit;
       }
       $time2 = strtotime(gmdate("H:i:s d-m-Y",time()+7*3600));
       
       if(($time2-$time)>300) 
       {
            $this->pub->DeleteSession('login_temp');
            $this->pub->DeleteSession('changepass_time');
            redirect(base_url());
       }
       
       $user = $this->pub->GetSession('login_temp');
	   $data['user']= $user['taikhoan'];
       $this->load->view('changepass',$data); 
   } 
   
    function savepass()
	{
	  
		if(!isset($_POST['mkmoi']))
             show_404();  
       /*$time =  $this->pub->GetSession('changepass_time');
       if(empty($time)) 
       {
            $this->pub->DeleteSession('login_temp');
            $this->pub->DeleteSession('changepass_time');
            redirect(base_url());
       }
       $time2 = strtotime(gmdate("H:i:s d-m-Y",time()+7*3600));
       */
       /*if(($time2-$time)>300) 
       {
            $this->pub->DeleteSession('login_temp');
            $this->pub->DeleteSession('changepass_time');
            redirect(base_url());
       }*/
       
        $user_session = $this->input->post('user_session');
		$passnew = $this->input->post('mkmoi');
        //$passnew2 = $user_session['password2'];
        //$captcha = $user_session['captcha'];
        /*if(strlen($passnew) < 1 ||  strlen($passnew2) < 1  ||  strlen($captcha) < 1){
            $this->pub->SetSession('changepass_time',strtotime(gmdate("H:i:s d-m-Y",time()+7*3600)));
            $this->pub->SetFlashData('loginerror',"Mật khẩu, nhắc lại mật khẩu và mã xác nhận không được trống");
            echo 2; exit;
        }
        */
        /*if($passnew != $passnew2){
            $this->pub->SetSession('changepass_time',strtotime(gmdate("H:i:s d-m-Y",time()+7*3600)));
            $this->pub->SetFlashData('loginerror',"Mật khẩu và nhắc lại mật khẩu không giống nhau");
             echo 2; exit;//redirect(base_url().'authorize/changepass'.url_suffix());
        }*/
        
        //$captcha = md5($captcha);
        //$captcha2 = $this->pub->GetSession('captcha_val');
        
        /*if($captcha != $captcha2){
            $this->pub->SetSession('changepass_time',strtotime(gmdate("H:i:s d-m-Y",time()+7*3600)));
            $this->pub->SetFlashData('loginerror',"Mã xác nhận không đúng");
             echo 2; exit; //redirect(base_url().'authorize/changepass'.url_suffix());
        }*/
        
       // $user=$this->input->post('user');		
        //$data['matkhau'] = 'PASSWORD('.mysql_real_escape_string($passnew).')';
		$logins = $this->pub->GetSession('login');
		$user = $logins['taikhoan'];
		$data['matkhau'] = "'".md5($passnew)."'";
	    $data['time_change_pass'] = gmdate("Y-m-d H:i:s",time()+7*3600);
        $data['doimatkhau'] = 0;
        try{
          $users = $this->pub->GetSession('login_temp');
          $users['doimatkhau'] = 0;
		  $this->_UpdateLogin($logins['id'],$data);
          $this->pub->DeleteSession('login_temp');
          $this->pub->DeleteSession('changepass_time');
          $this->pub->SetSession('login',md5($users['id']));
          echo 1; exit; //redirect(base_url().'home'.url_suffix());
        }
        catch(Exception $e)
        {
           echo $e;
        }
	}   
    
    function captcha()
    {
		$captcha = $this->pub->Create_capcha('captcha_val');   
    }
    
   
    
    /*private function _GetLogin($user,$pass)
	{
		
         
			
		   return (int)$this->model ->select('id')
                                    ->where('taikhoan',mysql_real_escape_string($user))
                                    ->where('matkhau',md5($pass))
									//->where('matkhau','PASSWORD('.mysql_real_escape_string($pass).')',false)
                                    ->where("thungrac",0)->find()->id;  
	}*/
    private function _GetLogin($user,$pass)
	{		
		$sql_taikhoan="SELECT `id` FROM (`nhanvien`) WHERE `taikhoan` = '".mysql_real_escape_string($user)."' AND `matkhau` = '".md5($pass)."' AND  `thungrac` = 0 ".$this->admin_phanmem1."" ;
		$taikhoan=$this->pub->ketnoi_sql($sql_taikhoan,'get');
        //print_r($taikhoan); exit();
		if(count($taikhoan)==0)
		{
			//S tinh toan update cho cot trangthai trong table lslogin
			//S viet update du lieu cho bang ls login ben PM quan ly user
			$trinhduyets=$_SERVER['HTTP_USER_AGENT'];
			$session_names = $this->pub->config['session_name'];
			$sitenames = $this->pub->config['sitename'];//print_r($session_names.'--'.$sitenames.'--'.json_encode($users).'--');exit;
			$sql_lslogin="INSERT INTO `lslogins` (`taikhoan`, `timedn`, `account`, `ip`, `trinhduyet`,`session_name`,`sitename`,`trangthaidangnhap`) 
			VALUES ('".mysql_real_escape_string($user)."', '".gmdate("Y-m-d H:i:s",time()+7*3600)."','', '".$_SERVER["REMOTE_ADDR"]."', '".$trinhduyets."','".$session_names."','".$sitenames."',1)";//print_r($sql_lslogin);exit;
           	$this->pub->ketnoi_sql($sql_lslogin,'update'); 
			//E viet update du lieu cho bang ls login ben PM quan ly user     
		//E tinh toan update cho cot trangthai trong table lslogin
			return 0;
		 	
		}
		else
		{
			$users = $this->_GetUser($taikhoan[0]['id']);
			$sql="SELECT `id` FROM (`nhanvien`) WHERE `taikhoan` = '".mysql_real_escape_string($user)."' AND `matkhau` = '".md5($pass)."' AND `thungrac` = 0 ".$this->admin_phanmem1."" ;
			$id=$this->pub->ketnoi_sql($sql,'get');	//print_r($sql);exit;	
			if(count($id)>0)
			{
				//update da update tro function_register
					return (int)$id[0]['id'];
			}
			else 
			{
				//S tinh toan update cho cot trangthai trong table lslogin
					//S viet update du lieu cho bang ls login ben PM quan ly user
					$trinhduyets=$_SERVER['HTTP_USER_AGENT'];
					$session_names = $this->pub->config['session_name'];
					$sitenames = $this->pub->config['sitename'];//print_r($session_names.'--'.$sitenames.'--'.json_encode($users).'--');exit;
					$sql_lslogin="INSERT INTO `lslogins` (`taikhoan`, `timedn`, `account`, `ip`, `trinhduyet`,`session_name`,`sitename`,`trangthaidangnhap`) 
					VALUES ('".mysql_real_escape_string($user)."', '".gmdate("Y-m-d H:i:s",time()+7*3600)."','".json_encode($users)."', '".$_SERVER["REMOTE_ADDR"]."', '".$trinhduyets."','".$session_names."','".$sitenames."',2)";//print_r($sql_lslogin);exit;
					$this->pub->ketnoi_sql($sql_lslogin,'update');// print_r($sql_lslogin);exit;
					//E viet update du lieu cho bang ls login ben PM quan ly user     
				//E tinh toan update cho cot trangthai trong table lslogin
				return 0;
			}
		}
		
		
		//return (int)$id[0]['id'];
           /*return (int)$this->model ->select('id')
                                    ->where('taikhoan',mysql_real_escape_string($user))
                                    ->where('matkhau',md5($pass))
									//->where('matkhau','PASSWORD('.mysql_real_escape_string($pass).')',false)
                                    ->where("thungrac",0)->find()->id;  */
	}
    
    private function _GetUser($id)
	{
	    /*$sql="SELECT `id`, `tennhanvien` as ten, `taikhoan`, `trungtam` as donvi, `chinhanh`, `groups`, `doimatkhau`, `hethanmatkhau`, `time_change_pass`, `bophan` 
				FROM (`nhanvien`) WHERE `id` = ".$id." AND `thungrac` = 0 ";*/
		if($this->taikhoan=='admin')
			$sql="SELECT nv.id, nv.tennhanvien as ten, nv.taikhoan, nv.trungtam as donvi, nv.chinhanh, usg.groups, nv.doimatkhau, nv.hethanmatkhau, nv.time_change_pass, nv.bophan, nv.mattcu, nv.mattmoi FROM nhanvien as nv,user_pm_groups as usg WHERE usg.taikhoan = nv.taikhoan and nv.id = '".$id."' AND `thungrac` = 0";
		else
			$sql="SELECT nv.id, nv.tennhanvien as ten, nv.taikhoan, nv.trungtam as donvi, nv.chinhanh, usg.groups, nv.doimatkhau, nv.hethanmatkhau, nv.time_change_pass, nv.bophan, nv.mattcu, nv.mattmoi FROM nhanvien as nv,user_pm_groups as usg WHERE usg.taikhoan = nv.taikhoan and nv.id = '".$id."' AND nv.phanmem LIKE '%,".$this->pub->config['session_name'].",%' AND `thungrac` = 0 and usg.phanmem = '".$this->pub->config['session_name']."'";
		//print_r($sql);exit;
		$user=$this->pub->ketnoi_sql($sql,'get');
		
		/*if(isset($user[0]['mattcu']))
		{
			$id_tt=$this->model->table("donvis")->select("id")->where("mattuser",$user[0]['mattcu'])->where('thungrac',0)->find()->id;
			$user[0]["donvi"]=$id_tt;
		}*/
		//print_r($kq[0])	;exit;
		/*if($user[0]["donvi"]==0)
			$user[0]["donvi"]='';*/
		//return $user[0];
		$this->pub->SetSession('login',$user[0]);	
		echo 1; exit;  
		//return (array)$user->where('thungrac',0)->find();
		/*$user = $this->model->select('id,ten,taikhoan,donvi,chinhanh,groups,doimatkhau,hethanmatkhau,time_change_pass,bophan')
                            ->where('id',$id);
        return (array)$user->where('thungrac',0)->find();*/
	}
    private function _UpdateLogin($account,$data)
	{
	   
	   // ".$this->admin_phanmem1."
	   $sql="UPDATE `nhanvien` SET `matkhau` = ".$data['matkhau'].", `time_change_pass` = '".$data['time_change_pass']."', `doimatkhau` = ".$data['doimatkhau']."
	     WHERE `id` = '".$account."' " ;//print_r($sql);exit;
		 $this->pub->ketnoi_sql($sql,'upadate');
		 
	   $this->pub->ketnoi_sql($sql,'update');	
		/*$this->model->where('id',$account)
                    ->set('matkhau',$data['matkhau'],false)
                    ->set('time_change_pass',$data['time_change_pass'])
                    ->set('doimatkhau',$data['doimatkhau'])
                    ->update();*/
	}  
    private function _UpdateLogout($id)
	{
		$sql="UPDATE `nhanvien` SET trangthai = 1 WHERE `id` = ".$id." ".$this->admin_phanmem1."" ;
		$this->pub->ketnoi_sql($sql,'update');//print_r($sql);exit;
		/*$this->model->where('id',$id)
                    ->update(array('trangthai'=>'1'));*/
	}	
}